﻿namespace Arms.Framework
{
    using System;
    using System.Reflection;

    public static class TypeExtensions
    {
        /// <summary>
        /// Finds the base class of this type
        /// </summary>
        /// <remarks>
        /// Factorial
        /// </remarks>
        /// <param name="source"></param>
        /// <returns></returns>
        public static Type FindBaseType(this Type source)
        {
            if (source.BaseType != null && source.BaseType.BaseType != null)
            {
                return FindBaseType(source.BaseType);
            }
            else if (source.BaseType != null && source.BaseType.BaseType == null)
            {
                return source;
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// Finds the specified property of this type
        /// </summary>
        /// <param name="source"></param>
        /// <param name="expressionID"></param>
        /// <returns></returns>
        public static PropertyInfo FindProperty(this Type source, string expressionID)
        {
            string[] names = expressionID.Split('.');

            PropertyInfo propertyInfo = null;
            Type propertyType = source;
            foreach (string name in names)
            {
                PropertyInfo info = propertyType.GetProperty(name);
                if (info != null)
                {
                    propertyInfo = info;
                    propertyType = info.PropertyType;
                }
                else
                {
                    break;
                }
            }

            return propertyInfo;
        }
    }
}